<template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @close="handleClose" @open="handleOpen">
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <div style="text-align: right">
        <el-button type="primary" @click="clickSubmit">确定</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/settings'
import { reqGetUserDetailById, reqAssignRole } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      roleList: [],
      checkList: [],
      loading: false
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = []
    },

    // Promise.all([promise对象1,promise对象2,...]).then() 所有promise对象异步操作完成时,才调用then方法
    handleOpen() {
      this.loading = true
      //   this.getRoleList()
      //   this.getUserDetailById()
      Promise.all([this.getRoleList(), this.getUserDetailById()]).then(() => {
        this.loading = false
      })
    },

    // 获取所有的角色列表
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 100)
      this.roleList = rows
    },

    // 获取员工的角色信息
    async getUserDetailById() {
      const { data: { roleIds }} = await reqGetUserDetailById(this.userId)
      this.checkList = roleIds
    },

    // 提交角色数据
    async clickSubmit() {
      await reqAssignRole(this.userId, this.checkList)

      this.$message.success('分配角色成功')
      this.handleClose()
    }

  }
}
</script>

<style scoped lang='scss'>

</style>
